package main

import (
	"context"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/data/binding"
	"fyne.io/fyne/v2/driver/desktop"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"log"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	go ListenCursor(ctx)
	myApp := app.NewWithID("com.example.myapp")
	myWindow := myApp.NewWindow("System Tray Example")
	myWindow.Resize(fyne.NewSize(400, 300))
	// 设置窗口内容
	serverIp := binding.NewString()
	status := binding.NewString()
	myWindow.SetContent(container.NewVBox(
		widget.NewLabelWithData(serverIp),
		widget.NewEntryWithData(serverIp),
		widget.NewButton("后台运行", func() { myWindow.Hide() }),
		widget.NewButton("开始监听", func() { _ = status.Set("开始监听") }),
		widget.NewButton("取消监听", func() { _ = status.Set("取消监听") }),
		widget.NewLabelWithData(status),
		widget.NewButton("退出", func() {
			cancel()
			myApp.Quit()
		}),
	))

	// 添加系统托盘
	addSystemTray(myApp, myWindow)

	myWindow.ShowAndRun()
}

func addSystemTray(a fyne.App, w fyne.Window) {
	if desk, ok := a.(desktop.App); ok {
		// 创建系统托盘菜单
		showItem := fyne.NewMenuItem("显示界面", func() { w.Show() })
		showItem.Icon = theme.ViewRefreshIcon() // 设置菜单项图标
		showCloseItem := fyne.NewMenuItem("隐藏界面", func() { w.Hide() })

		quitItem := fyne.NewMenuItem("退出", func() { a.Quit() })
		quitItem.Icon = theme.CancelIcon() // 设置菜单项图标

		menu := fyne.NewMenu("控制客户端", showItem, quitItem, showCloseItem)
		desk.SetSystemTrayMenu(menu)

		// 设置系统托盘图标
		icon, err := fyne.LoadResourceFromPath("../static/icon/icon.png") // 替换为你的图标路径
		if err != nil {
			log.Println("Failed to load icon:", err)
		} else {
			desk.SetSystemTrayIcon(icon)
		}
	}
}
